package splab.ufcg.edu.br.trace.testlink.util;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;

import splab.ufcg.edu.br.trace.exceptions.ConnectionException;



public class Connector implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4938862491702343825L;

	private ConnectionProperties properties;

	public Connector() {

	}

	public ConnectionProperties getProperties() {
		return properties;
	}

	public void setProperties(ConnectionProperties properties) {
		this.properties = properties;
	}

	/**
	 * Connect to testlink database
	 * 
	 * @return SQL Connection
	 * @throws ConnectionException if connection cannot be established
	 */
	public Connection getConnection() throws ConnectionException {

		
		Connection connection = null;

		StringBuilder jdbcURL = new StringBuilder();
		jdbcURL.append("jdbc:mysql://");
		jdbcURL.append(properties.getUrl());
		jdbcURL.append("/");
		jdbcURL.append(properties.getDbname());

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection(jdbcURL.toString(),
					properties.getUsername(), properties.getPassword());
		} catch (Exception ex) {
			throw new ConnectionException(ex.getMessage(), ex);
		} 

		return connection;
	}

}
